package com.study.ibatis.io.session;

import com.study.ibatis.io.cfg.Configuration;
import com.study.ibatis.io.proxy.MapperProxy;
import com.study.utils.DataSourceUtil;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

public class DefaultSqlSession implements SqlSession{
    private Configuration defaultConfig;
    private Connection conn;
    public DefaultSqlSession(Configuration configuration){
        defaultConfig=configuration;
        this.conn= DataSourceUtil.getConnection(defaultConfig);
    }
    public <T> T getMapper(Class<T> iUserDaoClass) {
        return (T) Proxy.newProxyInstance(iUserDaoClass.getClassLoader(),new Class[]{iUserDaoClass},new MapperProxy(defaultConfig.getMappers(),conn));

    }

    public void close() {
        if(conn!=null){
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }}

    }
}
